package com.ft.base.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ft.base.web.advice.LocalStateCode;
import com.ft.common.utils.text.StringUtils;


/**
 * @author mdc mdc@comit.com.cn
 * maidachao comit
 * -ft-
 */
public class BaseController {
	
	protected static Logger log = LoggerFactory.getLogger(BaseController.class);

	/**
	 * out输出流
	 * 
	 * @param response
	 * @param string
	 * @param contentType
	 */
	protected void printString(HttpServletResponse response, String string, String contentType) {

		PrintWriter out = null;
		try {
			response.setHeader("Cache-Control", "no-cache");
			if (contentType == null || "".equals(contentType)) {
				response.setContentType("text/html; charset=UTF-8");
			} else {
				response.setContentType(contentType);
			}
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.write(string);
			out.close();
		}

	}

	/**
	 * 获取JSON字符串
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	public static String getRequestParamsStr(HttpServletRequest request)
			throws IOException, UnsupportedEncodingException {
		String jsonStr = null;
		if (null != request) {
			InputStream in = request.getInputStream();
			if (null != in) {
				jsonStr = inputStream2Str(in);
			}
		}
		return jsonStr;
	}
	
	/**
	 * inputStream转为字符串
	 * 
	 * @param in
	 *            输入流
	 * @return 结果字符串
	 * @throws IOException
	 */
	private static String inputStream2Str(InputStream in) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
		StringBuffer buffer = new StringBuffer();
		String line = "";
		while ((line = reader.readLine()) != null) {
			buffer.append(line);
		}
		return buffer.toString();
	}

	/**
	 * 判断是否为空
	 * 
	 * @param args
	 * @return
	 */
	protected boolean isEmpty(Object... args) {
		if (args == null || args.length == 0) {
			return true;
		}
		for (Object o : args) {
			if (o == null || "".equals(o)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 判断Map中的值是否为空
	 * 
	 * @param m
	 * @param args
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	protected boolean isEmptyInMap(Map m, Object... keys) {
		if (m == null) {
			log.info("map is null");
			return true;
		}
		if (keys == null || keys.length == 0) {
			return true;
		}
		for (Object o : keys) {
			if (isEmpty(m.get(o))) {
				log.info("isEmptyInMap key:" + o + " is null");
				return true;
			}
		}
		return false;
	}

	/**
	 * 构造执行失败结果
	 * 
	 * @param message
	 *            执行失败提示
	 * @return
	 */
	@SuppressWarnings("static-access")
	protected JsonView getExeFailView(String message) {
		JsonView JSONView = new JsonView();
		JSONView.setReturnCode(LocalStateCode.RETURN_EXE_FAIL);
		JSONView.setReturnMsg(message);
		return JSONView;
	}

	/**
	 * 构造执行成功结果
	 * 
	 * @param message
	 *            执行成功提示
	 * @return
	 */
	@SuppressWarnings("static-access")
	protected JsonView getSuccView(String message) {
		JsonView JSONView = new JsonView();
		JSONView.setReturnCode(LocalStateCode.RETURN_SUCC);
		JSONView.setReturnMsg(message == null ? "成功" : message);
		return JSONView;
	}

	/**
	 * 构造数据为空返回结果
	 * 
	 * @param message
	 *            数据为空返回提示
	 * @return
	 */
	protected JsonView getNullErrorView(String message) {
		JsonView jsonView = new JsonView();
		jsonView.setReturnCode(LocalStateCode.RETURN_NULL_ERROR);
		jsonView.setReturnMsg(message);
		return jsonView;
	}

	/**
	 * 过载保护，漏桶算法
	 * 
	 * @return
	 */
	protected boolean leakyBucketLimit(String capacity_key) {
		return false;
	}

	/**
	 * 获取Ip地址
	 * @param request
	 * @return
	 */
	public static String getIpAdrress(HttpServletRequest request) {
		String Xip = request.getHeader("X-Real-IP");
		String XFor = request.getHeader("X-Forwarded-For");
		if(StringUtils.isNullOrEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
			//多次反向代理后会有多个ip值，第一个ip才是真实ip
			int index = XFor.indexOf(",");
			if(index != -1){
				return XFor.substring(0,index);
			}else{
				return XFor;
			}
		}
		XFor = Xip;
		if(!StringUtils.isNullOrEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
			return XFor;
		}
		if (StringUtils.isNullOrEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
			XFor = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isNullOrEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
			XFor = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isNullOrEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
			XFor = request.getHeader("HTTP_CLIENT_IP");
		}
		if (StringUtils.isNullOrEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
			XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (StringUtils.isNullOrEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
			XFor = request.getRemoteAddr();
		}
		return XFor;
	}
	
}
